package com.zjxmyq.microserviceyida;

import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import com.aliyun.tea.TeaException;
import com.zjxmyq.microserviceyida.domain.AccessTokenManager;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class YidaUtils {
    /**
     * 使用 Token 初始化账号Client
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dingtalkoauth2_1_0.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkoauth2_1_0.Client(config);
    }

    public static AccessTokenManager refreshAccessToken() {
        try {
            com.aliyun.dingtalkoauth2_1_0.Client client = YidaUtils.createClient();
            com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest getAccessTokenRequest = new com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest()
                .setAppKey("dingkodcuposp9elh5bl")
                .setAppSecret("8_LfSvEMdC45rLwTrNKvJzDgUnnQqS64rs6I2IjXc0jtb7OVJI4eOh_b3SDQf9Oo");
            GetAccessTokenResponse accessToken = client.getAccessToken(getAccessTokenRequest);
            AccessTokenManager accessTokenManager = new AccessTokenManager();
            String tokenStr = accessToken.getBody().getAccessToken();
            accessTokenManager.setAccessToken(tokenStr);
            accessTokenManager.setExpiresAt(accessToken.getBody().getExpireIn());
            return accessTokenManager;
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                log.error(err.message);
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                log.error(err.message);
            }

        }
        return null;
    }
}
